/* 
 * File:   delivery_cleaner.h
 * Author: james
 *
 * Created on 2011年3月25日, 上午11:01
 */

#ifndef DELIVERY_CLEANER_H
#define	DELIVERY_CLEANER_H

#include "prepare.h"
#include <map>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/thread.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/function.hpp>
#include <unistd.h>

namespace edm
{
    namespace prepare
    {
        //!
        class delivery_cleaner_t
        {
        public:
            delivery_cleaner_t();
            ~delivery_cleaner_t();
            //! start cleaner
            int start(callback_clean_t callback_clean, callback_error_t callback_error);
            //! stop cleaner
            int stop();
            //! trigger clean
            void trigger_wait_nohang();
            void trigger_wait_hang();
            void trigger_clear();
            //! insert a new clean delivery
            void delivery_clean(pid_t pid, delivery_t* delivery);
            void clear(pid_t pid, int status);
        private:
            void clear_i(pid_t pid, int status);
            void trigger_wait_i(bool hang);
            void trigger_clear_i();
            void delivery_clean_i(pid_t pid, delivery_t* delivery);
        private:
            //! identify whether service is running
            bool m_started;
            //! callback clean
            callback_clean_t m_callback_clean;
            //! callback error
            callback_error_t m_callback_error;
            //! io service object of boost for deadline time and thread working
            boost::asio::io_service m_io_service;
            //! io service work object of boost for keeping io service is running
            boost::scoped_ptr<boost::asio::io_service::work> m_io_work;
            //! the timer to clean
            //! boost::asio::deadline_timer m_timer;
            //! thread pool
            boost::scoped_ptr<boost::thread> m_thread;
            //! should clean items map
            std::map<pid_t, delivery_t*> m_deliverys;
        };
    }
}


#endif	/* DELIVERY_CLEANER_H */

